package gui;

import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;
import rsshunter.RSSBase;

/**
 * Model of JList which is containing RSSBases.
 */
public class BasesListModel extends AbstractListModel {

    private List<RSSBase> bases = new ArrayList<RSSBase>();

    /**
     * Add RSSBase to model.
     */
    public void addBase(RSSBase base) {
        bases.add(base);
        fireIntervalAdded(this, bases.size(), bases.size());
    }

    /**
     * Get RSSBase from model.
     *
     * @param name Name of the base.
     */
    public RSSBase getBase(String name) {
        for (RSSBase base : bases) {
            if (name.equals(base.getName())) {
                return base;
            }
        }
        return null;
    }

    /**
     * Get RSSBase from model.
     *
     * @param index Index of the base.
     */
    public RSSBase getBase(int index) {
        return bases.get(index);
    }

    /**
     * Remove given RSSBase from model.
     */
    public void removeBase(RSSBase base) {
        bases.remove(base);
        fireIntervalRemoved(this, bases.size(), bases.size());
    }

    /**
     * Get list of all bases in model.
     *
     * @return List of all bases.
     */
    public List<RSSBase> getBasesList() {
        return bases;
    }

    /**
     * Change name of base existing in model.
     *
     * @param oldName Name of the base in model.
     * @param newName New name for found base.
     */
    public void changeBaseName(String oldName, String newName) {
        for (RSSBase base : bases) {
            if (oldName.equals(base.getName())) {
                base.setName(newName);
                return;
            }
        }
        fireContentsChanged(this, 0, bases.size());
    }

    /**
     * Set RSSBase at given index in model.
     */
    public void setElementAt(RSSBase base, int index) {
        bases.set(index, base);
        fireContentsChanged(this, index, index);
    }

    /**
     * Remove base at given index.
     */
    public void removeElementAt(int index) {
        bases.remove(index);
        fireIntervalRemoved(this, index, index);
    }

    /**
     * @return Number of bases in model.
     */
    @Override
    public int getSize() {
        return bases.size();
    }

    /**
     * Get base at given index.
     *
     * @return Object with RSSBase.
     */
    @Override
    public Object getElementAt(int index) {
        return bases.get(index).getName();
    }
}
